/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable no-console */
import { useEffect } from 'react';
import { proxy, ref, useSnapshot } from 'valtio';

// 破案了，是valtio本身的bug
// 与 class 无关

interface IPanel {
   key: string | number;
   otherKey: string | number;
}

interface Root {
  panel: IPanel;
}

// 无区别
// panel = new PanelService();
// panel = ref(proxy(new PanelService()));

const Editor = ({ service }: { service: Root }) => {
  console.count('Editor render');

  useEffect(() => {
    console.log('mount');
    /** 在useEffect中的 只修改依赖项意外的数据 会导致额外2次render */
    // service.panel.key = Math.random(); // 产生1次额外的render，是正常的，会合并不正常的render
    // service.panel.otherKey = Math.random(); // 产生2次额外的render，是不正常的，是valtio的bug

    window.setTimeout(()=>{
      // service.panel.key = Math.random(); // 产生1次额外的render，是正常的，会合并不正常的render
      service.panel.otherKey = Math.random(); // 不会产生额外的render
    },0);
  }, [service]);

  return <div >
    Root:
    <button onClick={() => { service.panel.key = Math.random(); }}>changeKey</button>
    <button onClick={() => { service.panel.otherKey = Math.random(); }}>changeOtherKey</button>

  </div>;
};

const Panel = ({ service }: { service: IPanel }) => {
  const snap = useSnapshot(service);
  console.count('Panel render');

  return <div >
    Panel:
    {snap.key}
  </div>;

};

const root = proxy({
  panel:{
    key:'',
    otherKey:'',
  }
});

const Test = () => {
  console.count('page count');
  return <div >
    <Editor service={root} />
    <Panel service={root.panel} />
  </div>;
};

export default Test;
